
//
//  StopToStopViewController.m
//  Bus_iPhone
//
//  Created by antunnel on 12-7-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "StopToStopViewController.h"
#import "BusDataManager.h"
#import "MBProgressHUD.h"
#import "StopToStopDetailViewController.h"

@interface StopToStopViewController ()

-(void)reloadStopTitle;

@end

@implementation StopToStopViewController

@synthesize tableView=_tableView;
@synthesize disSearchBar=_disSearchBar;
@synthesize startStop=_startStop;
@synthesize endStop=_endStop;
@synthesize searchArray=_searchArray;
@synthesize startStopDic=_startStopDic;
@synthesize endStopDic=_endStopDic;
@synthesize stopTitleLabel=_stopTitleLabel;
@synthesize searchBusResultArray=_searchBusResultArray;

-(void)dealloc{

    [_tableView release];
    [_searchBusResultArray release];
    [_disSearchBar release];
    [_startStop release];
    [_endStop release];
    [_searchArray release];
    [_startStopDic release];
    [_endStopDic release];
    [_stopTitleLabel release];
    [super dealloc];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:@"StopToStopViewController" bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    [self reloadStopTitle];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)setStartStopDic:(NSDictionary *)startStopDic{

    if ([_startStopDic isEqualToDictionary:startStopDic]) {
        return;
    }
    [_startStopDic release];
    _startStopDic=[startStopDic retain];
    
    self.startStop.text=[startStopDic objectForKey:@"stopName"];
    [self reloadStopTitle];
}


-(void)setEndStopDic:(NSDictionary *)endStopDic{

    if ([_endStopDic isEqualToDictionary:endStopDic]) {
        return;
    }
    [_endStopDic release];
    _endStopDic=[endStopDic retain];
    self.endStop.text=[endStopDic objectForKey:@"stopName"];
    [self reloadStopTitle];
}


-(void)reloadStopTitle{

    NSString *startText=nil;
    if (_startStopDic) {
        startText=[_startStopDic objectForKey:@"stopName"];
    }else {
        startText=@"(空)";
    }
    
    NSString *endText=nil;
    if (_endStopDic) {
        endText=[_endStopDic objectForKey:@"stopName"];
    }else {
        endText=@"(空)";
    }
    
    NSString *titleText=[NSString stringWithFormat:@"起点:%@\n终点:%@",startText,endText];
    self.stopTitleLabel.text=titleText;
    self.searchBusResultArray=nil;
}


-(IBAction)searchBtnDone:(id)sender{

    if (_startStopDic==nil) {
        [self showAlertWithTitle:@"提示" msg:@"起点站没有设置!"];
        return;
    }
    
    if (_endStopDic==nil) {
        [self showAlertWithTitle:@"提示" msg:@"终点站没有设置"];
        return;
    }
    
    MBProgressHUD *hud=[[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:hud];
    [hud showWhileExecuting:@selector(doSearch) onTarget:self withObject:nil animated:YES];
    [hud release];
}

-(void)doSearch{
    
    if (_startStopDic==nil) {
        [self showAlertWithTitle:@"提示" msg:@"起始站点没有选择!"];
        return;
    }
    
    if (_endStopDic==nil) {
        [self showAlertWithTitle:@"提示" msg:@"终点站点没有选择!"];
        return;
    }

    if ([_startStopDic isEqualToDictionary:_endStopDic]) {
        [self showAlertWithTitle:@"提示" msg:@"起始站点和终点站点不能为同一站点!"];
        return;
    }
    
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
    
    BusDataManager *busManage=[BusDataManager currentBusDataManager];
    
    NSArray *array=[busManage queryDirectBusLineStartStopID:[_startStopDic objectForKey:@"stopID"] endStopID:[_endStopDic objectForKey:@"stopID"]];
    if (array&&array.count>0) {
        isDie=YES;
    }else {
        isDie=NO;
        array=[busManage queryTwoRideStartStopID:[_startStopDic objectForKey:@"stopID"] endStopID:[_endStopDic objectForKey:@"stopID"]];
    }
    
    self.searchBusResultArray=array;
    
    if ([NSThread isMainThread]) {
        [self.tableView reloadData];
    }else {
        [_tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
    }
    [pool release];
}

#pragma mark -UISearchBarDelegate

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{

    if ([searchBar isEqual:_disSearchBar]) {
        return YES;
    }else {
        currentSearchBar=searchBar;
        
        if ([searchBar isEqual:_startStop]) {
            _disSearchBar.placeholder=@"起点站";
        }else {
            _disSearchBar.placeholder=@"终点站";
        }
        [_disSearchBar becomeFirstResponder];
        
        return NO;
    }
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    if ([searchBar isEqual:_startStop]&&searchText.length==0) {
        self.startStopDic=nil;
    }
    
    if ([searchBar isEqual:_endStop]&&searchText.length==0) {
        self.endStopDic=nil;
    }
    self.searchArray=[[BusDataManager currentBusDataManager]fuzzyQueryBusStopListWithFuzzyWord:searchText];
}

-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    
    return YES;
}

#pragma mark -UITableViewDataSource

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([tableView isEqual:_tableView]) {
        if (isDie) {
            return 45.0f;
        }else {
            return 60.0f;
        }
    }else {
        return 45.0f;
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if ([tableView isEqual:_tableView]) {
        return _searchBusResultArray.count;
    }
    
    return _searchArray.count;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    if ([tableView isEqual:_tableView]) {
        NSString *startStopName=nil;
        if (_startStopDic) {
            startStopName=[_startStopDic objectForKey:@"stopName"];
        }else {
            startStopName=@"(空)";
        }
        
        NSString *endStopName=nil;
        if (_endStopDic) {
            endStopName=[_endStopDic objectForKey:@"stopName"];
        }else {
            endStopName=@"(空)";
        }
        return [NSString stringWithFormat:@"从 %@ 到 %@ 线路",startStopName,endStopName];
    }else {
        return nil;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([tableView isEqual:_tableView]) {
        static NSString *cellString=@"result list";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellString];
        if (!cell) {
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellString] autorelease];
        }
        NSDictionary *dic=[_searchBusResultArray objectAtIndex:indexPath.row];
        if (isDie) {
            NSString *isGo=nil;
            if ([[dic objectForKey:@"type"] isEqualToString:@"0"]) {
                isGo=@"上行";
            }else {
                isGo=@"下行";
            }
            cell.textLabel.text=[NSString stringWithFormat:@"%@ %@",[dic objectForKey:@"lineName"],isGo];
        }else {
            NSMutableString *tempString=[NSMutableString stringWithString:@""];
            NSDictionary *tempStartLineInfo=[dic objectForKey:@"startLineInfo"];
            NSDictionary *tempEndLineInfo=[dic objectForKey:@"endLineInfo"];
            NSArray *tempSameStopArray=[dic objectForKey:@"sameStop"];
            NSDictionary *firstSameStop=[tempSameStopArray objectAtIndex:0];
            
            NSString *startLineName=[tempStartLineInfo objectForKey:@"lineName"];
            NSString *endLineName=[tempEndLineInfo objectForKey:@"lineName"];
            
            NSInteger startStopCount=-[[tempStartLineInfo objectForKey:@"theIndex"]intValue]+[[firstSameStop objectForKey:@"theIndex"]intValue];
            [tempString appendFormat:@"先乘坐 %@ 公交 %d 站 (%d站)后 转乘 %@ ",startLineName,startStopCount,[tempSameStopArray count],endLineName];
            cell.textLabel.text=tempString;
            cell.textLabel.numberOfLines=0;
        }
        
        return cell;
        
    }else{
    static NSString *cellString=@"search list ";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellString];
        if (!cell) {
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellString] autorelease];
        }
        NSDictionary *dic=[_searchArray objectAtIndex:indexPath.row];
        cell.textLabel.text=[dic objectForKey:@"stopName"];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([tableView isEqual:_tableView]) {
        
        NSDictionary *dic=[_searchBusResultArray objectAtIndex:indexPath.row];
       // NSLog(@"dic %@",dic);
        if (isDie) {
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"BusLineDetailNotination" object:dic];
        }else {
            BusDataManager *busManage=[BusDataManager currentBusDataManager];
            NSString *startStopID=[dic objectForKey:@"s_lineID"];
            NSDictionary *tempStartLineDic=[dic objectForKey:@"startLineInfo"];
            NSArray *tempSameStops=[dic objectForKey:@"sameStop"];
            NSDictionary *firstSameStopDic=[tempSameStops objectAtIndex:0];
            NSString *s_fromIndex=[tempStartLineDic objectForKey:@"theIndex"];
            NSString *s_toIndex=[firstSameStopDic objectForKey:@"theIndex"];
            NSArray *tempStartStopArray=[busManage querySingleBusLineByBusID:startStopID type:[dic objectForKey:@"s_type"] fromIndex:s_fromIndex toIndex:s_toIndex];
            
            NSString *endStopID=[dic objectForKey:@"e_lineID"];
            NSDictionary *lastSameStopDic=[tempSameStops lastObject];
            NSDictionary *tempEndLineDic=[dic objectForKey:@"endLineInfo"];
           // NSString *e_fromIndex=[lastSameStopDic objectForKey:@"theIndex"];
            NSString *e_toIndex=[tempEndLineDic objectForKey:@"theIndex"];
            NSArray *tempEndStopArray=[busManage querySingleBusLineByBusID:endStopID type:[dic objectForKey:@"e_type"] fromIndex:@"0" toIndex:e_toIndex];
           // NSLog(@"temp end %@",tempEndStopArray);
            
            NSInteger tempIndex=0;
            for (NSDictionary *t_dic in tempEndStopArray) {
                if ([[t_dic objectForKey:@"stopName"] isEqualToString:[lastSameStopDic objectForKey:@"stopName"]]) {
                    tempIndex=[tempEndStopArray indexOfObject:t_dic];
                    break;
                }
            }
           
            tempEndStopArray=[tempEndStopArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(tempIndex, [tempEndStopArray count]-tempIndex)]];
            StopToStopDetailViewController *stop=[[StopToStopDetailViewController alloc]initWithNibName:nil bundle:nil];
            stop.title=@"详情";
            stop.startStopArray=tempStartStopArray;
            stop.endStopArray=tempEndStopArray;
            stop.dataDic=dic;
            [self.navigationController pushViewController:stop animated:YES];
            [stop release];
        }
    }else {
        
        if ([currentSearchBar isEqual:_startStop]) {
            self.startStopDic=[_searchArray objectAtIndex:indexPath.row];
        }else if ([currentSearchBar isEqual:_endStop]) {
            self.endStopDic=[_searchArray objectAtIndex:indexPath.row];
        }
    }
    
    [self.searchDisplayController setActive:NO animated:YES];
}

#pragma mark -UISearchDisviewController

- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{

    _startStop.hidden=YES;
    _endStop.hidden=YES;
}

-(void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller{

    _startStop.hidden=NO;
    _endStop.hidden=NO;
}
@end
